<?php

namespace app\admin\controller\manufacture;

use app\common\controller\Backend;
use think\Db;

/**
 * 报表统计
 *
 * @icon fa fa-chart-bar
 * @remark 数据分析和报表生成
 */
class Report extends Backend
{
    /**
     * 生产报表
     */
    public function production()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        // 获取生产统计数据
        $data = $this->getProductionData($startDate, $endDate);
        $this->view->assign('data', $data);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 质量报表
     */
    public function quality()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        // 获取质量统计数据
        $data = $this->getQualityData($startDate, $endDate);
        $this->view->assign('data', $data);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 库存报表
     */
    public function inventory()
    {
        // 获取库存统计数据
        $data = $this->getInventoryData();
        $this->view->assign('data', $data);
        
        return $this->view->fetch();
    }

    /**
     * 设备报表
     */
    public function equipment()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        // 获取设备统计数据
        $data = $this->getEquipmentData($startDate, $endDate);
        $this->view->assign('data', $data);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 成本报表
     */
    public function cost()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        // 获取成本统计数据
        $data = $this->getCostData($startDate, $endDate);
        $this->view->assign('data', $data);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 综合报表
     */
    public function comprehensive()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        // 获取综合统计数据
        $data = $this->getComprehensiveData($startDate, $endDate);
        $this->view->assign('data', $data);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 导出报表
     */
    public function export()
    {
        $type = $this->request->get('type', 'production');
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        switch ($type) {
            case 'production':
                $data = $this->getProductionData($startDate, $endDate);
                $filename = '生产报表_' . date('YmdHis') . '.xlsx';
                break;
            case 'quality':
                $data = $this->getQualityData($startDate, $endDate);
                $filename = '质量报表_' . date('YmdHis') . '.xlsx';
                break;
            case 'inventory':
                $data = $this->getInventoryData();
                $filename = '库存报表_' . date('YmdHis') . '.xlsx';
                break;
            case 'equipment':
                $data = $this->getEquipmentData($startDate, $endDate);
                $filename = '设备报表_' . date('YmdHis') . '.xlsx';
                break;
            case 'cost':
                $data = $this->getCostData($startDate, $endDate);
                $filename = '成本报表_' . date('YmdHis') . '.xlsx';
                break;
            default:
                $this->error('未知的报表类型');
        }
        
        // 这里应该实现Excel导出功能
        // 由于篇幅限制，这里只返回数据
        return json(['data' => $data, 'filename' => $filename]);
    }

    /**
     * 获取生产数据
     */
    private function getProductionData($startDate, $endDate)
    {
        $data = [];
        
        // 计划统计
        $data['plan'] = [
            'total' => \app\admin\model\manufacture\Plan::whereTime('createtime', 'between', [$startDate, $endDate])->count(),
            'completed' => \app\admin\model\manufacture\Plan::whereTime('updatetime', 'between', [$startDate, $endDate])->where('status', 'completed')->count(),
            'running' => \app\admin\model\manufacture\Plan::where('status', 'running')->count(),
            'pending' => \app\admin\model\manufacture\Plan::where('status', 'pending')->count(),
        ];
        
        // 按天统计
        $data['daily'] = [];
        $start = strtotime($startDate);
        $end = strtotime($endDate);
        
        for ($i = $start; $i <= $end; $i += 86400) {
            $date = date('Y-m-d', $i);
            $created = \app\admin\model\manufacture\Plan::whereTime('createtime', $date)->count();
            $completed = \app\admin\model\manufacture\Plan::whereTime('updatetime', $date)->where('status', 'completed')->count();
            
            $data['daily'][] = [
                'date' => date('m-d', $i),
                'created' => $created,
                'completed' => $completed
            ];
        }
        
        // 按产品统计
        $data['byProduct'] = \app\admin\model\manufacture\Plan::alias('p')
            ->join('scanwork_order o', 'p.order_id = o.id')
            ->join('scanwork_order_model om', 'o.id = om.order_id')
            ->join('scanwork_product_model pm', 'om.model_id = pm.id')
            ->join('scanwork_product pr', 'pm.product_id = pr.id')
            ->whereTime('p.createtime', 'between', [$startDate, $endDate])
            ->field('pr.name as product_name, COUNT(p.id) as plan_count, SUM(om.quantity) as total_quantity')
            ->group('pr.id')
            ->order('plan_count desc')
            ->select();
        
        return $data;
    }

    /**
     * 获取质量数据
     */
    private function getQualityData($startDate, $endDate)
    {
        $data = [];
        
        // 质检统计
        $data['quality'] = [
            'total' => \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])->count(),
            'pass' => \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])->where('result', 'pass')->count(),
            'fail' => \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])->where('result', 'fail')->count(),
            'pending' => \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])->where('result', 'pending')->count(),
        ];
        
        // 计算合格率
        if ($data['quality']['total'] > 0) {
            $data['quality']['pass_rate'] = round(($data['quality']['pass'] / $data['quality']['total']) * 100, 2);
        } else {
            $data['quality']['pass_rate'] = 0;
        }
        
        // 按天统计
        $data['daily'] = [];
        $start = strtotime($startDate);
        $end = strtotime($endDate);
        
        for ($i = $start; $i <= $end; $i += 86400) {
            $date = date('Y-m-d', $i);
            $total = \app\admin\model\manufacture\Quality::whereTime('createtime', $date)->count();
            $pass = \app\admin\model\manufacture\Quality::whereTime('createtime', $date)->where('result', 'pass')->count();
            $passRate = $total > 0 ? round(($pass / $total) * 100, 2) : 0;
            
            $data['daily'][] = [
                'date' => date('m-d', $i),
                'total' => $total,
                'pass' => $pass,
                'pass_rate' => $passRate
            ];
        }
        
        // 按检验类型统计
        $data['byType'] = \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])
            ->field('type, COUNT(*) as count, SUM(CASE WHEN result = "pass" THEN 1 ELSE 0 END) as pass_count')
            ->group('type')
            ->select();
        
        return $data;
    }

    /**
     * 获取库存数据
     */
    private function getInventoryData()
    {
        $data = [];
        
        // 库存统计
        $data['stock'] = [
            'total_materials' => \app\admin\model\manufacture\Material::count(),
            'total_quantity' => \app\admin\model\manufacture\Stock::sum('quantity'),
            'low_stock' => \app\admin\model\manufacture\Stock::alias('s')
                ->join('manufacture_material m', 's.material_id = m.id')
                ->where('s.quantity', '<=', Db::raw('m.min_stock'))
                ->where('m.min_stock', '>', 0)
                ->count(),
            'total_value' => \app\admin\model\Stock::alias('s')
                ->join('manufacture_material m', 's.material_id = m.id')
                ->sum(Db::raw('s.quantity * m.unit_price')),
        ];
        
        // 按仓库统计
        $data['byWarehouse'] = \app\admin\model\manufacture\Stock::alias('s')
            ->join('manufacture_warehouse w', 's.warehouse_id = w.id')
            ->field('w.warehouse_name, COUNT(s.id) as material_count, SUM(s.quantity) as total_quantity')
            ->group('s.warehouse_id')
            ->select();
        
        // 按分类统计
        $data['byCategory'] = \app\admin\model\manufacture\Stock::alias('s')
            ->join('manufacture_material m', 's.material_id = m.id')
            ->join('manufacture_material_category mc', 'm.category_id = mc.id')
            ->field('mc.name as category_name, COUNT(s.id) as material_count, SUM(s.quantity) as total_quantity')
            ->group('m.category_id')
            ->select();
        
        return $data;
    }

    /**
     * 获取设备数据
     */
    private function getEquipmentData($startDate, $endDate)
    {
        $data = [];
        
        // 设备统计
        $data['equipment'] = [
            'total' => \app\admin\model\manufacture\Equipment::count(),
            'normal' => \app\admin\model\manufacture\Equipment::where('status', 'normal')->count(),
            'maintenance' => \app\admin\model\manufacture\Equipment::where('status', 'maintenance')->count(),
            'fault' => \app\admin\model\manufacture\Equipment::where('status', 'fault')->count(),
            'idle' => \app\admin\model\manufacture\Equipment::where('status', 'idle')->count(),
        ];
        
        // 计算设备利用率
        if ($data['equipment']['total'] > 0) {
            $data['equipment']['utilization_rate'] = round(($data['equipment']['normal'] / $data['equipment']['total']) * 100, 2);
        } else {
            $data['equipment']['utilization_rate'] = 0;
        }
        
        // 维护记录统计
        $data['maintenance'] = [
            'total' => \app\admin\model\manufacture\Maintenance::whereTime('createtime', 'between', [$startDate, $endDate])->count(),
            'routine' => \app\admin\model\manufacture\Maintenance::whereTime('createtime', 'between', [$startDate, $endDate])->where('maintenance_type', 'routine')->count(),
            'repair' => \app\admin\model\manufacture\Maintenance::whereTime('createtime', 'between', [$startDate, $endDate])->where('maintenance_type', 'repair')->count(),
        ];
        
        // 按设备类型统计
        $data['byType'] = \app\admin\model\manufacture\Equipment::field('type, COUNT(*) as count')
            ->group('type')
            ->select();
        
        return $data;
    }

    /**
     * 获取成本数据
     */
    private function getCostData($startDate, $endDate)
    {
        $data = [];
        
        // 成本统计
        $data['cost'] = [
            'total' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->sum('amount'),
            'material' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->where('type', 'material')->sum('amount'),
            'labor' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->where('type', 'labor')->sum('amount'),
            'equipment' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->where('type', 'equipment')->sum('amount'),
            'energy' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->where('type', 'energy')->sum('amount'),
            'overhead' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->where('type', 'overhead')->sum('amount'),
        ];
        
        // 按天统计
        $data['daily'] = [];
        $start = strtotime($startDate);
        $end = strtotime($endDate);
        
        for ($i = $start; $i <= $end; $i += 86400) {
            $date = date('Y-m-d', $i);
            $amount = \app\admin\model\manufacture\Cost::whereTime('createtime', $date)->sum('amount');
            
            $data['daily'][] = [
                'date' => date('m-d', $i),
                'amount' => $amount ?: 0
            ];
        }
        
        // 按成本类型统计
        $data['byType'] = \app\admin\model\manufacture\Cost::alias('c')
            ->join('manufacture_cost_type ct', 'c.cost_type_id = ct.id')
            ->whereTime('c.createtime', 'between', [$startDate, $endDate])
            ->field('ct.name, SUM(c.amount) as total_amount, COUNT(c.id) as count')
            ->group('c.cost_type_id')
            ->order('total_amount desc')
            ->select();
        
        return $data;
    }

    /**
     * 获取综合数据
     */
    private function getComprehensiveData($startDate, $endDate)
    {
        $data = [];
        
        // 综合统计
        $data['summary'] = [
            'plan_count' => \app\admin\model\manufacture\Plan::whereTime('createtime', 'between', [$startDate, $endDate])->count(),
            'plan_completed' => \app\admin\model\manufacture\Plan::whereTime('updatetime', 'between', [$startDate, $endDate])->where('status', 'completed')->count(),
            'quality_count' => \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])->count(),
            'quality_pass' => \app\admin\model\manufacture\Quality::whereTime('createtime', 'between', [$startDate, $endDate])->where('result', 'pass')->count(),
            'equipment_normal' => \app\admin\model\manufacture\Equipment::where('status', 'normal')->count(),
            'equipment_total' => \app\admin\model\manufacture\Equipment::count(),
            'cost_total' => \app\admin\model\manufacture\Cost::whereTime('createtime', 'between', [$startDate, $endDate])->sum('amount'),
        ];
        
        // 计算关键指标
        if ($data['summary']['plan_count'] > 0) {
            $data['summary']['plan_completion_rate'] = round(($data['summary']['plan_completed'] / $data['summary']['plan_count']) * 100, 2);
        } else {
            $data['summary']['plan_completion_rate'] = 0;
        }
        
        if ($data['summary']['quality_count'] > 0) {
            $data['summary']['quality_pass_rate'] = round(($data['summary']['quality_pass'] / $data['summary']['quality_count']) * 100, 2);
        } else {
            $data['summary']['quality_pass_rate'] = 0;
        }
        
        if ($data['summary']['equipment_total'] > 0) {
            $data['summary']['equipment_utilization_rate'] = round(($data['summary']['equipment_normal'] / $data['summary']['equipment_total']) * 100, 2);
        } else {
            $data['summary']['equipment_utilization_rate'] = 0;
        }
        
        return $data;
    }
}
